package com.pospi.pospihold.ui.cash_ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.pospihold.R;
import com.pospi.pospihold.adapter.RestOrderAdapter;
import com.pospi.pospihold.dao.OrderDao;
import com.pospi.pospihold.dto.GoodsDto;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.dto.RestOrderBeen;
import com.pospi.pospihold.http.LoadServer;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.util.Api;
import com.pospi.pospihold.util.SaveOrderInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class RestOrderActivity extends BaseActivity {

    @Bind(R.id.lv_order)
    ListView lvOrder;
    @Bind(R.id.rv_order)
    RecyclerView rv_order;

    private List<RestOrderBeen> orderDtos = new ArrayList<>();
    public static final String REST_ORDER = "restOrder";
    public static final String REST_SCAN = "scan";
    public static final String REST_Point = "point_select";


    private OrderDao orderDao;
    private MyAdapter adapter;
    private RestOrderBeen orderBeen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_rest_order);
        setTitle("取单");
        ButterKnife.bind(this);
//        orderDao = new OrderDao(getApplicationContext());
//
//        orderDtos = orderDao.selectRestOrder();
//        RestOrderAdapter adapter = new RestOrderAdapter(getApplicationContext(), orderDtos);
//        lvOrder.setAdapter(adapter);
//        lvOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Intent intent;
//                if (orderDtos.get(position).getPayReturn().equals(REST_SCAN)) {
//                    intent = new Intent(RestOrderActivity.this, ScanReceiptActivity.class);
//                } else {
//                    intent = new Intent(RestOrderActivity.this, PointSelectActivity.class);
//                }
//                Bundle bundle = new Bundle();
//                bundle.putSerializable(REST_ORDER, orderDtos.get(position));
//                intent.putExtras(bundle);
//                startActivity(intent);
//                Log.i("跳转之前", "NO" + orderDtos.get(position).getMaxNo() + "");
//
//                boolean delete = orderDao.deleteRestOrderInfo(orderDtos.get(position).getMaxNo());
//                Log.i("delete", delete + "");
//                finish();
//            }
//        });
        init();

    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    adapter.notifyDataSetChanged();
                    break;
                case 2:
                    break;
                case 3:
                    Intent intent = new Intent(RestOrderActivity.this, PointSelectActivity.class);
                    intent.putExtra("order", orderBeen);
                    startActivity(intent);
                    RestOrderActivity.this.finish();
                    break;
            }
        }
    };

    private void init() {
        rv_order.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyAdapter(R.layout.item_order, orderDtos);
        rv_order.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                orderBeen = orderDtos.get(position);
                getMsg(orderBeen.getSid());
                deleteOrder(orderBeen.getSid());

            }
        });
        getData();
    }

    private void getMsg(String sid) {
        RequestParams params = new RequestParams();
        params.put("sid", sid);
        LoadServer.getConnect(this, Api.GET_ORDER_MSG, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("data", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    JSONArray array = object.getJSONArray("Value");
                    List<GoodsDto> list = new ArrayList<GoodsDto>();
                    for (int j = 0;j<array.length();j++) {
                        JSONObject jsonObject = array.getJSONObject(j);
                        GoodsDto dto = new GoodsDto();
                        dto.setSid(jsonObject.getString("menus_sid"));
                        dto.setName(jsonObject.getString("menus_name"));
                        dto.setPrice(Double.parseDouble(jsonObject.getString("m_price")));
                        dto.setNum(Integer.parseInt(jsonObject.getString("number")));
                        if (!dto.getName().substring(0, 1).equals("-")) {
                            list.add(dto);
                        }

                    }
                    orderBeen.setMsg(SaveOrderInfo.changeGoodDtoToJson(list));
                    Message message = Message.obtain();
                    message.what = 3;

                    handler.sendMessage(message);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    private class MyAdapter extends BaseQuickAdapter<RestOrderBeen ,BaseViewHolder>{

        public MyAdapter(@LayoutRes int layoutResId, @Nullable List<RestOrderBeen> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, RestOrderBeen item) {
            helper.setText(R.id.tv_tableNo, item.getTableNo());
            helper.setText(R.id.tv_orderTime, item.getYyyymmdd()+" "+item.getHhmmss());
            helper.setText(R.id.tv_orderAmount, "￥"+item.getTotalAmount());
        }
    }
    private void getData(){
        RequestParams params = new RequestParams();
        //得到店铺的Id
        SharedPreferences preferences = getSharedPreferences("StoreMessage", Context.MODE_PRIVATE);
        String id = preferences.getString("Id", "");//得到店铺的ID
        params.put("shopNo", id);
        LoadServer.getConnect(this, Api.GET_ORDER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("data", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    JSONArray array = object.getJSONArray("Value");
                    List<RestOrderBeen> orderBeens = new Gson().fromJson(array.toString(), new TypeToken<List<RestOrderBeen>>() {
                    }.getType());
                    orderDtos.clear();
                    orderDtos.addAll(orderBeens);
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Message message = Message.obtain();
                message.what = 2;
                handler.sendMessage(message);

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }
    private void deleteOrder(String sid){
        RequestParams params = new RequestParams();
        params.put("sid", sid);
        LoadServer.getConnect(this, Api.DEL_ORDER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("data", new String(bytes));

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }
}
